import {
  createContext,
  useContext,
  useState,
  type PropsWithChildren,
} from "react";
import AudioPlayer from "@/lib/utils/audio";

const AudioContext = createContext<AudioPlayer | null>(null);

export function useAudioPlayer() {
  const player = useContext(AudioContext);

  if (!player) {
    throw new Error("`useAudioPlayer` must used inside `AudioPlayerProvider`");
  }

  return player;
}

export default function AudioPlayerProvider({ children }: PropsWithChildren) {
  const [player] = useState(() => {
    const player = new AudioPlayer();

    player.load("alert", "/alert.mp3");

    return player;
  });
  return (
    <AudioContext.Provider value={player}>{children}</AudioContext.Provider>
  );
}
